import datetime
from db import db
from flask import Blueprint, request,jsonify
import json,math
from projectcom import fileupload
from utils.myredis import r

g_blue=Blueprint('goods',__name__)

# 分类管理
@g_blue.route('cateM',methods=['POST','GET'])
def cateM():
    if request.method=='POST':
        data=json.loads(request.data)
        userid=int(data['userid'])
        type=int(data['type'])
        name=data['name']
        sort=int(data['sort'])
        ctime=datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
        print(ctime)

        sql="insert into category(type,name,sort,create_time,update_time,create_user,update_user) values(%d,'%s',%d,'%s',%d,%d)"%(type,name,sort,ctime,ctime)
        db.update(sql)
        db.commit()
        return jsonify({
            'code':200
        })
    else:
        # 一共有多少条
        sql="select count(id) as count from category"
        res=db.find(sql)
        total=res['count']

        # 每页显示多少条
        page_size=3
        # 当前第几页
        page=int(request.args.get('page',1))
        # 极端总共多少也
        tpage=int(math.ceil(total/page_size))
        # 获取当前页面数据
        start=(page-1)*page_size
        sql1="select * from category limit %d,%d"%(start,page_size)
        tres=db.find_all(sql1)
        return jsonify({
            'code':200,
            'total':total,
            'page_size':page_size,
            'tpage':tpage,
            'list':tres
        })


# 上传图片的视图
@g_blue.route('/uploader',methods=['POST'])
def uploader():
    file=request.files.get('file')
    res=fileupload(file)
    return jsonify({
        'code':200,
        'url':res
    })


@g_blue.route('disM',methods=['GET','POST'])
def disM():
    if request.method=="GET":
        page_size=2
        page=int(request.args.get('page',1))
        # 获取大于1
        if page>=1:
            # 从redis中查询上一页最大值，如果没有，如果存在where
            prepage=page-1
            max=r.get_str('dis'+str(prepage))
            if max:
                sql="select * from dish where id>%d limit 0,%d"%(max,page_size)

            else:
                start=(int(page)-1)*page_size
                sql="select * from dish limit 0,%d"%(start,page_size)
            res=db.find_all(sql)
            # 存入redis
            r.set_str("dish"+str(page),str(res[-1:][0]['id']))
        return jsonify({
            'code':200,
            'total':100,
            "page_size":page_size,
            'list':'res'
        })
    else:
        # 添加菜品

        # 获取参数
        id=request.args.get('id')

        # 加入数据库

        # 清除分页缓存数据
        r.remove_str('dish')








